package sort;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-15
 * Time: 22:31
 */
public class CountSort {
    public static void main(String[] args) {

        int[] arr = {2, 1, 32, 1, 32, 1, 32, 1, 3};
        countSort(arr);
        System.out.println(Arrays.toString(arr));
    }
    //计数排序
    public static void countSort(int[] arr) {
        int maxVal = arr[0];
        int minVal = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (maxVal < arr[i]) {
                maxVal = arr[i];
            }
            if (minVal > arr[i]) {
                minVal = arr[i];
            }
        }
        int len = maxVal - minVal + 1;//数组的长度（考虑到负数）
        int[] count = new int[len];
        //统计原数组中各个数出现的次数
        for (int j : arr) {
            count[j - minVal]++;
        }
        int index = 0;
        for (int i = 0; i < count.length; i++) {
            while (count[i] > 0) {
                arr[index++] = i + minVal;
                count[i]--;
            }
        }
    }

}
